package org.jeecg.modules.home.monitoring.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xkcoding.http.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.bicycle.order.entity.BikeVehicleOrder;
import org.jeecg.modules.bicycle.order.mapper.BikeVehicleOrderMapper;
import org.jeecg.modules.bicycle.vehicle.entity.BikeVehicle;
import org.jeecg.modules.bicycle.vehicle.mapper.BikeVehicleMapper;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.home.monitoring.entity.MonitoringMap;
import org.jeecg.modules.home.monitoring.entity.MonitoringPile;
import org.jeecg.modules.home.monitoring.entity.MonitoringStation;
import org.jeecg.modules.home.monitoring.mapper.MonitoringMapper;
import org.jeecg.modules.home.monitoring.service.MonitoringService;
import org.jeecg.modules.home.monitoring.vo.MonitoringMapReq;
import org.jeecg.modules.param.area.entity.BikeSysUserArea;
import org.jeecg.modules.param.area.mapper.BikeSysUserAreaMapper;
import org.jeecg.modules.param.pile.entity.BikePile;
import org.jeecg.modules.param.pile.mapper.BikePileMapper;
import org.jeecg.modules.param.station.entity.BikeStation;
import org.jeecg.modules.param.station.entity.BikeStationHeartbeat;
import org.jeecg.modules.param.station.mapper.BikeStationHeartbeatMapper;
import org.jeecg.modules.param.station.mapper.BikeStationMapper;
import org.jeecg.modules.param.station.vo.HomeReport;
import org.jeecg.modules.param.sysparam.entity.BikeSysParam;
import org.jeecg.modules.param.sysparam.service.IBikeSysParamService;
import org.jeecg.modules.threadpool.MyThreadPoolTaskExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 月月鸟
 */
@Service
public class MonitoringServiceImpl implements MonitoringService {
    @Resource
    private MonitoringMapper monitoringMapper;

    @Resource
    private BikeSysUserAreaMapper bikeSysUserAreaMapper;

    @Resource
    private BikePileMapper bikePileMapper;

    @Resource
    private BikeVehicleMapper bikeVehicleMapper;

    @Resource
    private BikeStationHeartbeatMapper bikeStationHeartbeatMapper;

    @Resource
    private IBikeSysParamService bikeSysParamService;

    @Resource
    private BikeStationMapper bikeStationMapper;

    @Resource
    private BikeVehicleOrderMapper bikeVehicleOrderMapper;



    @Override
    public Result<?> homeList(MonitoringStation monitoringStation, Integer pageNo, Integer pageSize) {
        Date date = new Date();
        //获取操作用户信息
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取区域权限
        QueryWrapper<BikeSysUserArea> userAreaQueryWrapper = new QueryWrapper<>();
        userAreaQueryWrapper.eq("user_id", principal.getUsername());
        BikeSysUserArea bikeSysUserArea = bikeSysUserAreaMapper.selectOne(userAreaQueryWrapper);
        if (bikeSysUserArea == null || StringUtils.isEmpty(bikeSysUserArea.getAreaId())) {
            return Result.OK();
        }
        //区域查询条件
        if (StringUtils.isNotEmpty(bikeSysUserArea.getAreaId())) {
            monitoringStation.setAreaUserArrayIds(Arrays.asList(bikeSysUserArea.getAreaId().split(",")));
        }

        if (StringUtils.isNotEmpty(monitoringStation.getAreaIds())) {
            monitoringStation.setAreaArrayIds(Arrays.asList(monitoringStation.getAreaIds().split(",")));
        }
        List<MonitoringStation> monitoringStationList = monitoringMapper.homeListView(monitoringStation);
        //添加跳包数据
        //获取报警参数 个人或全局
        List<BikeSysParam> list = bikeSysParamService.getList();
        List<MonitoringStation> homeList = addHeartList(monitoringStationList,list);
        //根据百分比筛选网点
        if (StringUtil.isNotEmpty(monitoringStation.getPileBikePercentStart())||StringUtil.isNotEmpty(monitoringStation.getPileBikePercentEnd())){
            for (int i = homeList.size() - 1; i >= 0; i--) {
                MonitoringStation tb = homeList.get(i);
                if (StringUtil.isNotEmpty(monitoringStation.getPileBikePercentStart())) {
                    double start = Double.parseDouble(monitoringStation.getPileBikePercentStart());
                    if (tb.getPileBikePercent() < start) {
                        homeList.remove(i);
                    }
                }
            }
            for (int i = homeList.size() - 1; i >= 0; i--) {
                MonitoringStation tb = homeList.get(i);
                if (StringUtil.isNotEmpty(monitoringStation.getPileBikePercentEnd())) {
                    double end = Double.parseDouble(monitoringStation.getPileBikePercentEnd());
                    if (tb.getPileBikePercent() > end){
                        homeList.remove(i);
                    }
                }
            }

        }
        return Result.OK(homeList);
    }



    @Override
    public Result<?> homeListById(MonitoringPile monitoringPile) {
        List<MonitoringPile> list = monitoringMapper.getPileByStationId(monitoringPile.getStationId());
        for (MonitoringPile tb : list) {
            if (StringUtils.isNotEmpty(tb.getMemo())) {
                String[] split = tb.getMemo().split(",");
                List<String> fault=new ArrayList<>();
                for (String a : split){
                    if (a.equals("正常")) {
                        fault.add("0");
                    }
                    if (a.equals("通信异常")) {
                        fault.add("1");
                    }
                    if (a.equals("用户卡读卡器异常")) {
                        fault.add("2");

                    }
                    if (a.equals("车辆读卡器异常")) {
                        fault.add("3");

                    }
                    if (a.equals("车辆RF异常")) {
                        fault.add("4");

                    }
                    if (a.equals("锁具关闭故障")) {
                        fault.add("5");

                    }
                    if (a.equals("限位开关常开故障")) {
                        fault.add("6");

                    }
                    if (a.equals("限位开关常闭故障")) {
                        fault.add("7");

                    }
                    if (a.equals("锁具打开故障")) {
                        fault.add("8");
                    }
                }
                fault.sort(new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        return o1.compareTo(o2);
                    }
                });
                tb.setPileFault(fault);
            }
        }
        return Result.OK(list);
    }

    @Override
    public Result<?> homeReport() {
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取区域权限
        QueryWrapper<BikeSysUserArea> userAreaQueryWrapper = new QueryWrapper<>();
        userAreaQueryWrapper.eq("user_id", principal.getUsername());
        BikeSysUserArea bikeSysUserArea = bikeSysUserAreaMapper.selectOne(userAreaQueryWrapper);
        if (bikeSysUserArea == null || StringUtils.isEmpty(bikeSysUserArea.getAreaId())) {
            return Result.OK();
        }
        HomeReport homeReport = new HomeReport();
        //网点数
        Integer stationCount = bikeStationMapper.selectCount(new QueryWrapper<BikeStation>().eq("status", 1).in("id", bikeSysUserArea.getAreaId().split(",")));
        homeReport.setStationCount(stationCount.toString());
        //网点在线数
        long time = new Date().getTime()-60000;
        Date date = new Date(time);
        int i = bikeStationMapper.onlineCount(date,bikeSysUserArea.getAreaId().split(","));
        homeReport.setOnlineCount(i+"");
        //车桩数
        Integer selectCount = monitoringMapper.selectPileCount(bikeSysUserArea.getAreaId().split(","));
        homeReport.setPileCount(selectCount.toString());
        //在桩车辆
        Integer vehicleCount = bikeVehicleOrderMapper.selectVehicleCount("1", bikeSysUserArea.getAreaId().split(","));
        homeReport.setVehiclePileCount(vehicleCount.toString());
        //获取借车次数
        Integer pickCount = bikeVehicleOrderMapper.selectPickCount();
        homeReport.setBorrowReturn(pickCount.toString());
        //获取当天还车次数
        Integer parkCount = bikeVehicleOrderMapper.selectParkCount();
        homeReport.setBorrowReturn(homeReport.getBorrowReturn() + "/" + parkCount.toString());
        return Result.OK(homeReport);
    }

    @Override
    public List<MonitoringStation> homeMapList(BikeStation bikeStation) {
        MonitoringStation monitoringStation = new MonitoringStation();
        //获取操作用户信息
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取区域权限
        QueryWrapper<BikeSysUserArea> userAreaQueryWrapper = new QueryWrapper<>();
        userAreaQueryWrapper.eq("user_id", principal.getUsername());
        BikeSysUserArea bikeSysUserArea = bikeSysUserAreaMapper.selectOne(userAreaQueryWrapper);
        if (bikeSysUserArea == null || StringUtils.isEmpty(bikeSysUserArea.getAreaId())) {
            return null;
        }
        if (StringUtils.isNotEmpty(bikeStation.getCode())){
            monitoringStation.setStationCode(bikeStation.getCode());
        }
        //区域查询条件
        if (StringUtils.isNotEmpty(bikeSysUserArea.getAreaId())) {
            monitoringStation.setAreaUserArrayIds(Arrays.asList(bikeSysUserArea.getAreaId().split(",")));
        }

        if (StringUtils.isNotEmpty(bikeStation.getAreaId())) {
            monitoringStation.setAreaArrayIds(Arrays.asList(bikeStation.getAreaId().split(",")));
        }
        List<MonitoringStation> monitoringStationList = monitoringMapper.homeListMapView(monitoringStation);
        //添加跳包数据
        //获取报警参数 个人或全局
        List<BikeSysParam> list = bikeSysParamService.getList();
        return addHeartList(monitoringStationList,list);
    }



    private List<MonitoringStation> addHeartList(List<MonitoringStation> homeList,List<BikeSysParam> list) {

        for (int i = 0; i < homeList.size(); i++) {
            MonitoringStation monitoringStation = homeList.get(i);
            //int vehicleCount = monitoringMapper.getVehicleCountByStationId(monitoringStation.getStationId());

            //跳包数据
            if (StringUtils.isEmpty(monitoringStation.getPileBikeCount())){
                monitoringStation.setPileBikeCount("0");
            }
            int vehicleCount =Integer.parseInt(monitoringStation.getPileBikeCount());
            //获取车数/桩数
            monitoringStation.setPileBikeCount(vehicleCount + "/" + monitoringStation.getPileCount());
            //增加在桩/车桩百分比
            String[] split = monitoringStation.getPileBikeCount().split("/");
            double bike = Double.parseDouble(split[0]);
            double pile = Double.parseDouble(split[1]);
            monitoringStation.setPileBikePercent((bike/pile)*100);

            if (monitoringStation.getHeartTime() != null) {
                DecimalFormat df = new DecimalFormat("0.0");
                //温度
                Double e = Double.valueOf(df.format(Double.valueOf(monitoringStation.getTemperature().toString().replace("E", ""))));
                monitoringStation.setTemperature(e);
                //电压
                monitoringStation.setVoltage(Double.valueOf(df.format(monitoringStation.getVoltage())));
                //湿度
                monitoringStation.setHumidity(Double.valueOf(df.format(monitoringStation.getHumidity())));

                //网点是否有车
                if (vehicleCount == 0) {
                    monitoringStation.setIsStationVehicle(BikeConstant.y_n_no);
                    monitoringStation.setAbnormal("2");
                } else {
                    monitoringStation.setIsStationVehicle(BikeConstant.y_n_yes);
                    monitoringStation.setAbnormal("1");
                }

                for (BikeSysParam tb : list) {
                    //警告网点停车总数报警上限

                    if (tb.getPName().equals("param002")) {
                        double parseInt = Integer.parseInt(tb.getPValue()) / 100.0;
                        double top = (double) vehicleCount / monitoringStation.getPileCount();
                        if (top > parseInt) {
                            monitoringStation.setWarnStopUp(BikeConstant.y_n_yes);
                        }
                    }
                    //警告网点停车总数报警下限
                    if (tb.getPName().equals("param003")) {
                        double parseInt = Integer.parseInt(tb.getPValue()) / 100.0;
                        double down = (double) vehicleCount / monitoringStation.getPileCount();
                        if (down < parseInt) {
                            monitoringStation.setWarnStopDown(BikeConstant.y_n_yes);
                        }
                    }
                    //车桩故障总数报警上限
                    if (tb.getPName().equals("param004")) {
                        int parseInt = Integer.parseInt(tb.getPValue());
                        int errCountTop = monitoringStation.getPileCount() * (parseInt / 100);
                        if (monitoringStation.getErrCount() > errCountTop) {
                            monitoringStation.setWarnErrUp(BikeConstant.y_n_yes);
                        }
                    }
                    //温度报警上限
                    if (tb.getPName().equals("param005")) {
                        Double temperature = monitoringStation.getTemperature();
                        Double pValue = Double.parseDouble(tb.getPValue());
                        if (pValue < temperature) {
                            monitoringStation.setWarnTemperatureUp(BikeConstant.y_n_yes);
                        }
                    }
                    //湿度报警上限
                    if (tb.getPName().equals("param011")) {
                        Double humidity = monitoringStation.getHumidity();
                        Double pValue = Double.parseDouble(tb.getPValue());
                        if (pValue < humidity) {
                            monitoringStation.setWarnHumidityUp(BikeConstant.y_n_yes);
                        }
                    }
                    //电压报警下限
                    if (tb.getPName().equals("param006")) {
                        Double voltage = monitoringStation.getVoltage();
                        Double pValue = Double.parseDouble(tb.getPValue());
                        if (pValue > voltage) {
                            monitoringStation.setWarnVoltageUp(BikeConstant.y_n_yes);
                        }
                    }

                }
                //是否故障
                if (monitoringStation.getErrCount() != 0) {
                    monitoringStation.setIsStationErr(BikeConstant.y_n_yes);
                    monitoringStation.setAbnormal("5");
                }
                //电量不足
                if (StringUtils.isNotEmpty(monitoringStation.getStationHeartStatus())){
                    String[] split1 = monitoringStation.getStationHeartStatus().split(";");
                    for (String vo : split1){
                        if (vo.equals("电量不足")){
                            monitoringStation.setAbnormal("7");
                        }
                    }
                }
                //判断常闭
                if (monitoringStation.getIsLock().equals(BikeConstant.y_n_yes)) {
                    monitoringStation.setAbnormal("3");
                }
                //网点是否断线
                long updateTime = new Date().getTime() - monitoringStation.getHeartTime().getTime();
                if (BikeConstant.is_offline_time < updateTime) {
                    monitoringStation.setIsOffline(BikeConstant.y_n_yes);
                    monitoringStation.setAbnormal("4");
                } else {
                    monitoringStation.setIsOffline(BikeConstant.y_n_no);
                }


            } else {
                //网点是否断线
                monitoringStation.setIsOffline(BikeConstant.y_n_yes);
                monitoringStation.setAbnormal("4");
            }
        }

        return homeList;
    }


}
